package org.dromara.netbar.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.AssertUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.netbar.domain.bo.NetbarProductStockLogBo;
import org.dromara.netbar.domain.vo.NetbarProductStockNumVo;
import org.dromara.netbar.mapper.NetbarProductStockLogMapper;
import org.dromara.netbar.service.INetbarProductStockLogService;
import org.springframework.stereotype.Service;
import org.dromara.netbar.domain.bo.NetbarProductBo;
import org.dromara.netbar.domain.vo.NetbarProductVo;
import org.dromara.netbar.domain.NetbarProduct;
import org.dromara.netbar.mapper.NetbarProductMapper;
import org.dromara.netbar.service.INetbarProductService;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 商品信息Service业务层处理
 *
 * @author ZhouWenTao
 * @date 2025-08-18
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NetbarProductServiceImpl implements INetbarProductService {

    private final NetbarProductMapper baseMapper;

    private final NetbarProductStockLogMapper productStockLogMapper;

    private final INetbarProductStockLogService productStockLogService;
    /**
     * 查询商品信息
     *
     * @param productId 主键
     * @return 商品信息
     */
    @Override
    public NetbarProductVo queryById(Long productId){
        NetbarProductVo netbarProductVo = baseMapper.selectVoById(productId);
        if (null != netbarProductVo) {
            // 获取库存数据
            List<NetbarProductStockNumVo> stockList = productStockLogMapper.selectProductStockByIds(Collections.singletonList(netbarProductVo.getProductId()));
            if (!stockList.isEmpty()) {
                netbarProductVo.setStock(stockList.get(0).getStock());
            }
        }

        return netbarProductVo;
    }

    /**
     * 分页查询商品信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商品信息分页列表
     */
    @Override
    public TableDataInfo<NetbarProductVo> queryPageList(NetbarProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NetbarProduct> lqw = buildQueryWrapper(bo);
        Page<NetbarProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        if(CollectionUtil.isNotEmpty(result.getRecords())){
            List<Long> productIdList = result.getRecords().stream().map(NetbarProductVo::getProductId).toList();
            // 获取库存数据
            List<NetbarProductStockNumVo> stockList = productStockLogMapper.selectProductStockByIds(productIdList);
            // 转换成Map方便查找
            Map<Long, Integer> stockMap = stockList.stream()
                .collect(Collectors.toMap(
                        NetbarProductStockNumVo::getProductId,
                        NetbarProductStockNumVo::getStock
                ));
            // 设置库存
            result.getRecords().forEach(item -> {
                Integer stockNum = stockMap.getOrDefault(item.getProductId(), 0);
                item.setStock(stockNum);
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商品信息列表
     *
     * @param bo 查询条件
     * @return 商品信息列表
     */
    @Override
    public List<NetbarProductVo> queryList(NetbarProductBo bo) {
        LambdaQueryWrapper<NetbarProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NetbarProduct> buildQueryWrapper(NetbarProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<NetbarProduct> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NetbarProduct::getProductId);
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), NetbarProduct::getProductName, bo.getProductName());
        lqw.eq(StringUtils.isNotBlank(bo.getProductCode()), NetbarProduct::getProductCode, bo.getProductCode());
        lqw.eq(StringUtils.isNotBlank(bo.getBarcode()), NetbarProduct::getBarcode, bo.getBarcode());
        lqw.eq(bo.getCategoryId() != null, NetbarProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getBrand()), NetbarProduct::getBrand, bo.getBrand());
        lqw.eq(StringUtils.isNotBlank(bo.getSpec()), NetbarProduct::getSpec, bo.getSpec());
        lqw.eq(StringUtils.isNotBlank(bo.getUnit()), NetbarProduct::getUnit, bo.getUnit());
        lqw.eq(bo.getSalePrice() != null, NetbarProduct::getSalePrice, bo.getSalePrice());
        lqw.eq(bo.getCostPrice() != null, NetbarProduct::getCostPrice, bo.getCostPrice());
        lqw.eq(bo.getWeight() != null, NetbarProduct::getWeight, bo.getWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), NetbarProduct::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增商品信息
     *
     * @param bo 商品信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NetbarProductBo bo) {
        NetbarProduct add = MapstructUtils.convert(bo, NetbarProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setProductId(add.getProductId());
        }
        return flag;
    }

    /**
     * 修改商品信息
     *
     * @param bo 商品信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NetbarProductBo bo) {
        NetbarProduct update = MapstructUtils.convert(bo, NetbarProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NetbarProduct entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商品信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public R<?> addStock(NetbarProductBo bo) {
        AssertUtils.notNull(bo.getProductId(), "商品ID不能为空");
        AssertUtils.notNull(bo.getStock(), "数量不能为空");
        AssertUtils.notTrue(bo.getStock() == 0, "数量不能为0");
        NetbarProductVo netbarProductVo = queryById(bo.getProductId());
        AssertUtils.notTrue(netbarProductVo.getStock() < Math.abs(bo.getStock()), "库存不足");
        try {
            NetbarProductStockLogBo netbarProductStockLogBo = new NetbarProductStockLogBo();
            netbarProductStockLogBo.setProductId(bo.getProductId());
            if (bo.getStock() < 0) {
                // 减库存
                netbarProductStockLogBo.setChangeType("2");
            }else{
                // 加库存
                netbarProductStockLogBo.setChangeType("1");
            }
            netbarProductStockLogBo.setChangeCount(bo.getStock());
            productStockLogService.insertByBo(netbarProductStockLogBo);
        }catch (Exception e){
            return R.fail("更新失败, " + e.getMessage());
        }
        return R.ok("更新成功");
    }

    @Override
    public R<?> removeStock(NetbarProductBo bo) {
        return null;
    }
}
